﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.DomainServices.Server;
using Scoreboard.Model.Services;
using Scoreboard.Model.Authentication;

namespace Scoreboard.Model
{
	public sealed class DomainServiceFactory : IDomainServiceFactory
	{
		private IDomainServiceFactory _defaultFactory;
		public DomainServiceFactory(IDomainServiceFactory defaultFactory)
		{
			_defaultFactory = defaultFactory;
		}

		public static void Setup()
		{
			if (!(DomainService.Factory is DomainServiceFactory))
			{
				DomainService.Factory = new DomainServiceFactory(DomainService.Factory);
			}
		}

		public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
		{
			if (domainServiceType == typeof(ScoreboardDomainService))
			{
				DomainServiceContext authServiceContext =
					new DomainServiceContext(context, DomainOperationType.Query);
				AuthenticationService authService =
					(AuthenticationService)_defaultFactory.CreateDomainService(typeof(AuthenticationService), authServiceContext);
				ScoreboardUser user = authService.GetUser();

				DomainService domainService = (DomainService)Activator.CreateInstance(domainServiceType, user);
				domainService.Initialize(context);
				return domainService;
			}
			else
			{
				return _defaultFactory.CreateDomainService(domainServiceType, context);
			}
		}

		public void ReleaseDomainService(DomainService domainService)
		{
			if (domainService is ScoreboardDomainService)
			{
				domainService.Dispose();
			}
			else
			{
				_defaultFactory.ReleaseDomainService(domainService);
			}
		}
	}
}
